﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyAudio : MonoBehaviour
{
    public static EnemyAudio instance;


    public float duration { get; private set; } = Single.NaN;
    float startTime;


    public AudioClip damagePlayerAudioClip;

    public new Camera camera;

    [HideInInspector]
    public Vector3 randomVec;


    void Start()
    {
        instance = this;
        NewEnemy();
    }

    void Update()
    {
        if (!float.IsNaN(duration))
        {
            float alpha = Math.Min(1.0f, (Time.time - startTime) / duration);
            if (alpha >= 1.0f)
            {
                Stop();

                var audioSource = GetComponent<AudioSource>();
                audioSource.transform.position = new Vector3(0, 0, 0);
                audioSource.PlayOneShot(damagePlayerAudioClip);

                StartCoroutine(DelayNewEnemy(6));
            }
            else UpdateAudioSource(alpha);
        }
    }

    public bool AnyEnemy()
    {
        return !float.IsNaN(duration);
    }

    public void Stop()
    {
        duration = Single.NaN;

        var audioSource = GetComponent<AudioSource>();
        audioSource.Stop();
        audioSource.volume = 1.0f;
    }

    public IEnumerator DelayNewEnemy(float seconds)
    {
        yield return new WaitForSeconds(seconds);
        NewEnemy();
    }

    public void NewEnemy()
    {
        duration = UnityEngine.Random.Range(8.0f, 16.0f);
        startTime = Time.time;

        randomVec = Quaternion.AngleAxis(UnityEngine.Random.Range(0.0f, 360.0f), Vector3.up) * Vector3.left;
        UpdateAudioSource(0.0f);

        GetComponent<AudioSource>().Play();
    }

    private void UpdateAudioSource(float alpha)
    {
        var audioSource = GetComponent<AudioSource>();

        Vector3 sourcePos = randomVec * duration * 2.0f;
        gameObject.transform.position = Vector3.Lerp(sourcePos, randomVec, alpha);

        float absAngle = Math.Abs(Vector3.Angle(-camera.transform.forward, EnemyAudio.instance.randomVec));
        if (absAngle <= 22.5f) audioSource.volume = Mathf.Lerp(0.25f, 1.0f, absAngle / 22.5f);
        else audioSource.volume = 1.0f;
    }
}
